package com.atguigu.daijia.common.login;

import com.atguigu.daijia.common.constant.DaiJiaCommonConstants;
import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class GuiguLoginAspect {

    @Resource
    private RedisTemplate redisTemplate;

    // 使用环绕通知，execution 后面是切入点表达式 指定对哪些规则的方法进行增强
    @Around("execution(* com.atguigu.daijia.*.controller.*.*(..)) && @annotation(guiguLogin)")
    public Object login(ProceedingJoinPoint joinPoint, GuiguLogin guiguLogin) throws Throwable {
        /*** 1 获取request对象，通过spring提供的工具类*/
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) attributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();

        /*** 2 得到request后，获取请求头上的token*/
        String token = request.getHeader(DaiJiaCommonConstants.TOKEN_STR);

        /*** 3 token为空，返回未登录提示*/
        if (!StringUtils.hasText(token)) {
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        /*** 4 token 不为空，查询redis*/
        String customerId = (String) redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        /*** 5 把用户id 放入ThreadLocal 里面*/
        if (StringUtils.hasText(customerId)) {
            AuthContextHolder.setUserId(Long.valueOf(customerId));
        }

        return joinPoint.proceed();
    }
}
